const path = require('path');
const webpack = require('webpack');
const ManifestPlugin = require('webpack-plugin-manifest');
const fs = require('fs');
const os = require('os');
const Uglify = require("uglifyjs-webpack-plugin");
const CleanWebpackPlugin = require('clean-webpack-plugin');
const ExtractTextPlugin = require("extract-text-webpack-plugin");

const pages = getDirectories('./assets/src/pages').reduce((l, r) => {
  l[r] = `./assets/src/pages/${r}`;
  return l;
}, {});

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath)
    .filter(file => fs.statSync(path.join(srcpath, file)).isDirectory());
}

module.exports = (env) => {
  console.log('NODE_ENV: ', env.NODE_ENV);
  const nodeEnv = env.NODE_ENV || 'development';
  const isProd = nodeEnv === 'production';
  
  const DEV_SERVER_PORT = 9001;
  const PUBLIC_PATH = isProd ? undefined : `http://${os.hostname()}:${DEV_SERVER_PORT}/dist/`;
  return {
    devtool: !isProd ? 'source-map' : undefined,
    entry: Object.assign({
      vendor: ['jquery/src/jquery'],
      commons: ['./assets/src/commons'],
    }, pages),
    module: {
      rules: [
        {
          test: /\.ts?$/,
          use: 'ts-loader',
          exclude: /node_modules/
        },
        { 
          test: /\.js$/, 
          exclude: /node_modules/, 
          loader: 'babel'
        },
        {
          test: /\.css$/,
          exclude: /node_modules/,
          loader: ExtractTextPlugin.extract('css-loader', 'style-loader') /*这里的写法注意下 */
        }
      ]
    },
    resolve: {
      modules: ['node_modules', path.resolve(__dirname, 'src')],
      extensions: [ ".tsx", ".ts", ".js" ]
    },
    output: {
      publicPath: PUBLIC_PATH,
      path: path.resolve(__dirname, './assets/dist'),
      filename: isProd ? '[name]/main[hash].js':'[name]/main.js',
      chunkFilename: '__chunks/[id].js',
    },
    plugins: isProd ? [
      new Uglify(),
      new ManifestPlugin(),
      new CleanWebpackPlugin(
        ['dist/**/*'],　 //匹配删除的文件
        {
          root: __dirname,       　　　　　　　　　　//根目录
          verbose:  true,        　　　　　　　　　　//开启在控制台输出信息
          dry:      false        　　　　　　　　　　//启用删除文件
        }
      ),
      new ExtractTextPlugin("[name]/css/main[hash].css")
    ] : [
      new ManifestPlugin(),
      new CleanWebpackPlugin(
        ['dist/**/*'],　 //匹配删除的文件
        {
          root: __dirname,       　　　　　　　　　　//根目录
          verbose:  true,        　　　　　　　　　　//开启在控制台输出信息
          dry:      false        　　　　　　　　　　//启用删除文件
        }
      ),
      new ExtractTextPlugin("[name]/css/main.css")
    ],
    devServer: {
      publicPath: PUBLIC_PATH,
      host: '0.0.0.0',
      port: DEV_SERVER_PORT,
      compress: true,
      headers: { 'Access-Control-Allow-Origin': '*' },
      disableHostCheck: true
    },
  }
};

